package base.utils

import android.app.Activity
import java.lang.ref.WeakReference
import java.util.*

/**
 * @author njmsir
 * Created by njmsir on 2017/9/1.
 */
class ActivityManager private constructor() {
    private var activityStack = Stack<WeakReference<Activity>>()

    //kotlin式的单例模式写法中的其中一种写法
    companion object {
        var activityManager = Instance.instance
    }

    private object Instance {
        val instance = ActivityManager()
    }

    //添加activity
    fun add(activity: Activity?) {
        if (activity != null) {
            val weakActivity = WeakReference<Activity>(activity)
            activityStack.push(weakActivity)
        }
    }

    //删除指定的activity
    fun remove(activity: Activity?) {
        val weakActivity = WeakReference<Activity>(activity)
        if (activity != null && activityStack.contains(weakActivity)) {
            activity.finish()
            activityStack.remove(weakActivity)
        }
    }

    //删除当前的activity
    fun removeCurrent() {
        val activity = activityStack.pop().get()
        activity?.finish()
    }

    //删除所有activity
    fun removeAll() {
        val iterator = activityStack.iterator()
        while (iterator.hasNext()) {
            val next = iterator.next()
            if (next != null && activityStack.contains(next)) {
                next.get()?.finish()
            }
            iterator.remove()
        }
    }

    //返回当前activity
    fun getCurrentActivity(): Activity? {
        var activity: Activity? = null
        if (!activityStack.empty()) {
            activity = activityStack.peek().get()
        }
        return activity
    }

}